from xml_parser import *
import xml.sax
import socket
from player import *
import gooeypy as gui
from gooeypy.const import *
import os.path
import threading
import pygame
import cPickle

class game_fetcher(threading.Thread):
    def __init__(self, game):
        threading.Thread.__init__(self)
        self.game = game
        self.game_list = []
        
    def run(self):
        req_xml = "<tank_game_info_request></tank_game_info_request>";
        infoHandler = game_info_handler_client()
        
        sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("", 1976))
        sock.settimeout(1)
        print "testing", self.game.game_menu.join_search_input.value
        sent = sock.sendto(req_xml, (self.game.game_menu.join_search_input.value, 1976))
        for i in range(5):
            try:
                infoHandler = game_info_handler_client()
                (data, addr) = sock.recvfrom(4000)
                xml.sax.parseString(data, infoHandler)
                if infoHandler.request_type == "game_info":
                    newGame = infoHandler.game
                    newGame['ip'] = addr[0]
                    newGame['type'] = "game_available"
                    pygame.event.post(pygame.event.Event(pygame.USEREVENT, {'details':newGame}))
            except:
                pass
        sock.close()

class game_launch_waiter(threading.Thread):
    def __init__(self, game):
        threading.Thread.__init__(self)
        self.game = game
        
    def run(self):
        sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("", 1976))
        sock.settimeout(5)
        
        handler = game_setup_handler_client()
        for i in range(5):
            try:
                (data, addr) = sock.recvfrom(4000)
                xml.sax.parseString(data, handler)
                if handler.request_type == "tank_game_start":
                    for p in handler.players:
                        if not p['callsign'] == self.game.config.callsign:
                            newPlayer = player(p['callsign'], "peer")
                            newPlayer.start_info['start_position'] = p['start_pos']
                        else:
                            newPlayer = player(p['callsign'], "local")
                            newPlayer.start_info['start_position'] = p['start_pos']
                            newPlayer.player_id = p['player_id']
                            self.game.config.local_player = newPlayer
                        newPlayer.player_id = p['player_id']
                        self.game.players[p['player_id']] = newPlayer
                    
                    misc = {'type':'game_launch'}
                    pygame.event.post(pygame.event.Event(pygame.USEREVENT, {'details':misc}))
                    
                    return True
                    break
            except:
                print "Error in try catch block starting at line 296 in game_menu.py"
        return False
        sock.close()

class player_ready_waiter(threading.Thread):
    def __init__(self, game):
        self.game = game
        self.game_logic = game.game_logic
        threading.Thread.__init__(self)
    
    def run(self):
        sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("", 1976))
        sock.settimeout(5)
        stop = False
        num_players = len(self.game.players)
        readies = 0
        while not stop:
            try:
                (data, addr) = sock.recvfrom(4000)
                details = cPickle.loads(data)
                if details['type'] == "player_ready":
                    pygame.event.post(pygame.event.Event(pygame.USEREVENT, {'details':details}))
                    readies+= 1
                    
                    return True
                    break
            except:
                pass
            if readies == num_players:
                stop = True
            if not self.game.main_loop:
                stop = True
        return False
        sock.close()

class game_menu(gui.Container):
    
    def setup(self, game):
        self.game = game
        self.start = None
        self.available_games = []
        self.game_fetcher = game_fetcher(game)
        self.game.event_handler.connect(pygame.USEREVENT, self.user_events)
        
        #callsign page
        self.callsign_page = gui.Container(width=self.game.screen_rect.w, height=self.game.screen_rect.h)
        bg_image_surf = pygame.image.load(os.path.join("data", "main_menu.png"))
        callsign_bg = gui.Image(bg_image_surf)
        
        callsign_label = gui.Label("Enter your Callsign, Soldier!", align="center", y=260, font_size=20)
        callsign_input = gui.Input(align="center", y=290)
        
        callsign_menubar = gui.VBox(align="left", valign="bottom", y=-200, x=50, spacing=20)
        callsign_continue_button = gui.Button("Continue")
        callsign_continue_button.connect(CLICK, self.callsign_to_start, callsign_input)
        callsign_quit_button = gui.Button("Desert")
        callsign_quit_button.connect(CLICK, self.game.stop_loop)
        callsign_menubar.add(callsign_continue_button)
        callsign_menubar.add(callsign_quit_button)
        
        self.callsign_page.add(callsign_bg)
        self.callsign_page.add(callsign_label)
        self.callsign_page.add(callsign_input)
        self.callsign_page.add(callsign_menubar)
        self.add(self.callsign_page)
        
        self.active = self.callsign_page
        self.callsign_page.active = True
        
        #starting page
        self.start = gui.Container(width=self.game.screen_rect.w, height=self.game.screen_rect.h)
        bg_image_surf = pygame.image.load(os.path.join("data", "main_menu.png"))
        start_bg = gui.Image(bg_image_surf)
        
        start_menubar = gui.VBox(align="left", valign="bottom", y=-200, x=50, spacing=20)
        start_host_button = gui.Button("Host Battle")
        start_join_button = gui.Button("Join Battle")
        start_quit_button = gui.Button("Desert")
        start_quit_button.connect(CLICK, self.game.stop_loop)
        start_menubar.add(start_host_button)
        start_menubar.add(start_join_button)
        start_menubar.add(start_quit_button)
        self.start.add(start_bg)
        self.start.add(start_menubar)
        self.add(self.start)
        
        self.start.active = False
        
        #host game page
        self.host_game = gui.Container(width=self.game.screen_rect.w, height=self.game.screen_rect.h)
        bg_image_surf = pygame.image.load(os.path.join("data", "main_menu.png"))
        host_bg = gui.Image(bg_image_surf)
        
        host_label = gui.Label("Host a Battle")
        host_game_label = gui.Label("Host Lobby")
        host_game_game_name_lbl = gui.Label("Game Name", align="left", x=220, y=250)
        host_game_game_name_inp = gui.Input(align="left", x=220, y=270)
        
        host_game_port_lbl = gui.Label("Port", align="left", x=470, y=250)
        host_game_port_inp = gui.Input("", 5, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", align="left", x=470, y=270, width=80)
        
        host_game_kills_lbl = gui.Label("Max Kills", align="left", x=220, y=320)
        host_game_kills_inp = gui.Input("5", 2, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", align="left", x=220, y=340, width=50)
        
        host_game_start_button = gui.Button("Start", align="left", x=490, y=340)
        
        host_game_inputs = {}
        host_game_inputs['name'] = host_game_game_name_inp
        host_game_inputs['port'] = host_game_port_inp
        host_game_inputs['kills'] = host_game_kills_inp
        
        host_menubar = gui.VBox(align="left", valign="bottom", y=-200, x=50, spacing=20)
        host_main_menu_button = gui.Button("Main Menu")
        host_quit_button = gui.Button("Desert")
        host_quit_button.connect(CLICK, self.game.stop_loop)
        host_menubar.add(host_main_menu_button)
        host_menubar.add(host_quit_button)
        self.host_game.add(host_bg)
        self.host_game.add(host_label)
        self.host_game.add(host_game_game_name_lbl)
        self.host_game.add(host_game_game_name_inp)
        self.host_game.add(host_game_port_lbl)
        self.host_game.add(host_game_port_inp)
        self.host_game.add(host_game_kills_lbl)
        self.host_game.add(host_game_kills_inp)
        self.host_game.add(host_game_start_button)
        self.host_game.add(host_menubar)
        self.add(self.host_game)
        
        self.host_game.active = False
        
        #join game page
        self.join_game = gui.Container(width=self.game.screen_rect.w, height=self.game.screen_rect.h)
        bg_image_surf = pygame.image.load(os.path.join("data", "main_menu.png"))
        join_bg = gui.Image(bg_image_surf)
        
        join_label = gui.Label("Join a Battle")
        
        join_search_lbl = gui.Label("IP Search", align="left", x=220, y=250)
        self.join_search_input = gui.Input("255.255.255.255", align="left", x=220, y=270)
        
        join_games_lbl = gui.Label("List of available Games", align="left", x=220, y=320)
        self.join_games_sb = gui.SelectBox(align="left", x=220, y=340, width=300, height=100, scrollable=True)
        
        join_refresh_bttn = gui.Button("Refresh", align="left", x=220, y=460)
        join_join_bttn = gui.Button("Join", align="left", y=460, x=468)
        
        join_menubar = gui.VBox(align="left", valign="bottom", y=-200, x=50, spacing=20)
        join_main_menu_button = gui.Button("Main Menu")
        join_quit_button = gui.Button("Desert")
        join_quit_button.connect(CLICK, self.game.stop_loop)
        join_menubar.add(join_main_menu_button)
        join_menubar.add(join_quit_button)
        self.join_game.add(join_bg)
        self.join_game.add(join_label)
        
        self.join_game.add(join_search_lbl)
        self.join_game.add(self.join_search_input)
        self.join_game.add(join_games_lbl)
        self.join_game.add(self.join_games_sb)
        self.join_game.add(join_refresh_bttn)
        self.join_game.add(join_join_bttn)
        
        self.join_game.add(join_menubar)
        self.add(self.join_game)
        
        self.join_game.active = False
        
        #join lobby
        self.join_lobby = gui.Container(width=self.game.screen_rect.w, height=self.game.screen_rect.h)
        bg_image_surf = pygame.image.load(os.path.join("data", "main_menu.png"))
        join_lobby_bg = gui.Image(bg_image_surf)
        
        join_lobby_label = gui.Label("We're just waiting for our orders now")
        
        join_lobby_menubar = gui.VBox(align="left", valign="bottom", y=-200, x=50, spacing=20)
        join_lobby_main_menu_button = gui.Button("Main Menu")
        join_lobby_quit_button = gui.Button("Desert")
        join_lobby_quit_button.connect(CLICK, self.game.stop_loop)
        join_lobby_menubar.add(join_lobby_main_menu_button)
        join_lobby_menubar.add(join_lobby_quit_button)
        self.join_lobby.add(join_lobby_bg)
        self.join_lobby.add(join_lobby_label)
        
        self.join_lobby.add(join_lobby_menubar)
        self.add(self.join_lobby)
        
        self.join_lobby.active = False
        
        #host lobby page
        self.host_lobby = gui.Container(width=self.game.screen_rect.w, height=self.game.screen_rect.h)
        host_lobby_bg = gui.Image(bg_image_surf)
        
        host_lobby_joined_lbl = gui.Label("Players", align="left", x=220, y=250)
        self.host_lobby_joined_sb = gui.SelectBox(align="left", x=220, y=270, width=200, height=100, scrollable=True)
        host_lobby_launch_button = gui.Button("Roll Out!", align="left", x=220, y=390)
        
        host_lobby_menubar = gui.VBox(align="left", valign="bottom", y=-200, x=50, spacing=20)
        host_game_button = gui.Button("Back")
        host_lobby_quit_button = gui.Button("Desert")
        host_lobby_quit_button.connect(CLICK, self.game.stop_loop)
        host_lobby_menubar.add(host_game_button)
        host_lobby_menubar.add(host_lobby_quit_button)
        
        self.host_lobby.add(host_lobby_bg)
        
        self.host_lobby.add(host_lobby_joined_lbl)
        self.host_lobby.add(self.host_lobby_joined_sb)
        self.host_lobby.add(host_lobby_launch_button)
        
        self.host_lobby.add(host_lobby_menubar)
        self.add(self.host_lobby)
        
        self.host_lobby.active = False
        
        #round lobby
        self.round_lobby = gui.Container(width=self.game.screen_rect.w, height=self.game.screen_rect.h)
        bg_image_surf = pygame.image.load(os.path.join("data", "main_menu.png"))
        round_lobby_bg = gui.Image(bg_image_surf)
        
        round_lobby_label = gui.Label("We're just waiting for our orders now")
        
        round_lobby_players_lbl = gui.Label("Players", align="left", x=220, y=250)
        self.round_lobby_players_sb = gui.SelectBox(align="left", x=220, y=270, width=400, height=100, scrollable=True)
        
        round_lobby_menubar = gui.VBox(align="left", valign="bottom", y=-200, x=50, spacing=20)
        round_lobby_ready_button = gui.Button("Ready")
        round_lobby_quit_button = gui.Button("Desert")
        round_lobby_quit_button.connect(CLICK, self.game.stop_loop)
        round_lobby_menubar.add(round_lobby_ready_button)
        round_lobby_menubar.add(round_lobby_quit_button)
        self.round_lobby.add(round_lobby_bg)
        self.round_lobby.add(round_lobby_label)
        self.round_lobby.add(round_lobby_players_lbl)
        self.round_lobby.add(self.round_lobby_players_sb)
        
        self.round_lobby.add(round_lobby_menubar)
        self.add(self.round_lobby)
        
        self.round_lobby.active = False
        
        #host round lobby
        self.host_round_lobby = gui.Container(width=self.game.screen_rect.w, height=self.game.screen_rect.h)
        bg_image_surf = pygame.image.load(os.path.join("data", "main_menu.png"))
        host_round_lobby_bg = gui.Image(bg_image_surf)
        
        host_round_lobby_label = gui.Label("We're just waiting for Everyone to be ready now")
        
        host_round_lobby_players_lbl = gui.Label("Players", align="left", x=220, y=250)
        self.host_round_lobby_players_sb = gui.SelectBox(align="left", x=220, y=270, width=400, height=100, scrollable=True)
        
        host_round_lobby_readies_lbl = gui.Label("Ready Players", align="left", x=220, y=390)
        self.host_round_lobby_readies_sb = gui.SelectBox(align="left", x=220, y=410, width=200, height=100, scrollable=True)
        
        host_round_lobby_menubar = gui.VBox(align="left", valign="bottom", y=-200, x=50, spacing=20)
        host_round_lobby_ready_button = gui.Button("Ready")
        host_round_lobby_quit_button = gui.Button("Desert")
        host_round_lobby_quit_button.connect(CLICK, self.game.stop_loop)
        host_round_lobby_menubar.add(host_round_lobby_ready_button)
        host_round_lobby_menubar.add(host_round_lobby_quit_button)
        self.host_round_lobby.add(host_round_lobby_bg)
        self.host_round_lobby.add(host_round_lobby_label)
        self.host_round_lobby.add(host_round_lobby_players_lbl)
        self.host_round_lobby.add(self.host_round_lobby_players_sb)
        self.host_round_lobby.add(host_round_lobby_readies_lbl)
        self.host_round_lobby.add(self.host_round_lobby_readies_sb)
        
        self.host_round_lobby.add(host_round_lobby_menubar)
        self.add(self.host_round_lobby)
        
        self.host_round_lobby.active = False
        
        #button bindings
        start_host_button.connect(CLICK, self.activate_menu, self.host_game)
        start_join_button.connect(CLICK, self.start_to_join)
        host_main_menu_button.connect(CLICK, self.activate_menu, self.start)
        join_main_menu_button.connect(CLICK, self.activate_menu, self.start)
        host_game_button.connect(CLICK, self.activate_menu, self.host_game)
        host_game_start_button.connect(CLICK, self.host_game_start, host_game_inputs)
        join_refresh_bttn.connect(CLICK, self.refresh_game_list)
        join_join_bttn.connect(CLICK, self.do_join_game)
        host_lobby_launch_button.connect(CLICK, self.launch_game)
        round_lobby_ready_button.connect(CLICK, self.set_ready)
        host_round_lobby_ready_button.connect(CLICK, self.set_ready)
    
    
    def activate_menu(self, menu):
        self.active.active = False
        self.active = menu
        self.active.active = True
    
    def callsign_to_start(self, inp):
        if not inp.value:
            return
        self.game.config.callsign = inp.value
        self.activate_menu(self.start)
    
    def start_to_join(self):
        self.activate_menu(self.join_game)
        self.game_fetcher.start()
    
    def host_game_start(self, inps):
        if not inps['name'].value:
            return
        if not inps['port'].value:
            return
        if not inps['kills'].value:
            return
        
        name = inps['name'].value
        try:
            port = int(inps['port'].value)
        except:
            return
        try:
            kills = int(inps['kills'].value)
        except:
            return
        
        self.game.config.game_name = name
        self.game.config.game_port = port
        self.game.config.max_kills = kills
        self.game.config.host = True
        self.game.add_local_player()
        self.host_lobby_joined_sb.add(self.game.players[0].callsign, 0)
        if not self.game.info_server_running:
            self.game.start_info_server()
        self.activate_menu(self.host_lobby)
    
    def refresh_game_list(self):
        if self.game_fetcher.isAlive():
            return
        self.game_fetcher = game_fetcher(self.game)
        self.available_games = []
        self.join_games_sb.clear()
        self.game_fetcher.start()
        
    def user_events(self, event):
        if event.details['type'] == "game_available":
            self.join_games_sb.add(str(event.details['name']), len(self.available_games))
            self.available_games.append(event.details)
        elif event.details['type'] == "player_join_game":
            self.game.add_network_player(event.details['callsign'], event.details['addr'])
            self.host_lobby_joined_sb.clear()
            for i in range(len(self.game.players)):
                self.host_lobby_joined_sb.add(str(self.game.players[i].callsign), i)
        elif event.details['type'] == "player_ready":
            readies = 0
            id = event.details['id']
            self.game.players[id].ready = True
            sb = self.host_round_lobby_readies_sb
            sb.clear()
            for i in self.game.players:
                play = self.game.players[i]
                if play.ready:
                    readies+= 1
                    sb.add(str(play.callsign), id)
            if readies == len(self.game.players):
                misc = {'type':'game_launch'}
                print "LAUNCH EVENT HOST"
                pygame.event.post(pygame.event.Event(pygame.USEREVENT, {'details':misc}))
                self.active.active = False
            
    
    def launch_game(self):
        misc = {'type':'game_launch'}
        print "LAUNCH EVENT HOST"
        pygame.event.post(pygame.event.Event(pygame.USEREVENT, {'details':misc}))
    
    def round_end(self):
        if self.game.config.host:
            sb = self.host_round_lobby_players_sb
            self.activate_menu(self.host_round_lobby)
        else:
            sb = self.round_lobby_players_sb
            self.activate_menu(self.round_lobby)
        sb.clear()
        self.host_round_lobby_readies_sb.clear()
        for i in self.game.players:
            play = self.game.players[i]
            play.ready = False
            st = play.callsign.ljust(30)
            st+= str(play.kills).ljust(8)
            st+= str(play.assists).ljust(8)
            st+= str(play.deaths).ljust(8)
            sb.add(str(st), 0)
        
        if self.game.config.host:
            self.ready_waiter = player_ready_waiter(self.game)
            self.ready_waiter.start()
        
    
    def run(self):
        pass
    """
        self.page = start_page
        if self.page == None:
            self.page = "start"
        while True:
            if self.page == "start":
                self.start()
            elif self.page == "briefing_room":
                self.briefing_room()
            elif self.page == "briefing_room_stupid":
                self.briefing_room_stupid()
            elif self.page == "host_game":
                self.host_game()
            elif self.page == "join_game":
                self.join_game()
            elif self.page == "host_lobby":
                self.host_lobby()
            elif self.page == "post_game":
                self.post_game()
            elif self.page == "deployment":
                self.deployment()
            elif self.page == "start_game":
                self.game.next_status = "start_game"
                self.next_page = "post_game"
                return
            elif self.page == "exit":
                self.game.next_status = "exit";
                break
            else:
                self.game.next_status = "exit"
                break
            
            if self.next_page:
                self.page = self.next_page
                self.next_page = ""
            else:
                self.page = "exit"
            
            print "\n-----------\n"
        
        return
        """
        
    """def start(self):
        callsign = raw_input("Enter you're callsign, soldier: ")
        
        if callsign:
            self.game.config.callsign = str(callsign)
            print "Welcome %s. Next stop the briefing room! Double time!" % self.game.config.callsign
            self.next_page = "briefing_room"
        else:
            self.next_page = "start"
    
    def briefing_room(self):
        print "Normally you'd be on latrine duty, but Charlie's been givin' us hell,"
        print "So you got three choices: "
        print "[h] Host a battle"
        print "[j] Join a battle"
        print "[x] Desert. But you'll be shot before you reach the mess hall. Hoo Rah"
        
        choice = raw_input("\nSo what'll it be, " + self.game.config.callsign + "?: ")
        if choice:
            if choice == "h":
                self.next_page = "host_game"
            elif choice == "j":
                self.next_page = "join_game"
            elif choice == "x":
                print "Alright latrine rat. I'm giving you a 10 second headstart!"
                self.next_page = "exit"
            else:
                self.next_page = "briefing_room_stupid"
        else:
            self.next_page = "briefing_room_stupid"
    
    def briefing_room_stupid(self):
        print "Listen up, Latrine rat! I only gave you three choices. I hate repeating"
        print "myself so pay real close attention before I lose my patience: "
        print "[h] Host a battle"
        print "[j] Join a battle"
        print "[x] Desert. But you'll be shot before you reach the mess hall. Hoo Rah"
        
        choice = raw_input("So what'll it be, " + self.game.config.callsign + "?: ")
        if choice:
            if choice == "h":
                self.next_page = "host_game"
            elif choice == "j":
                self.next_page = "join_game"
            elif choice == "x":
                print "Alright latrine rat. I'm giving you a 10 second headstart!"
                self.next_page = "exit"
            else:
                self.next_page = "briefing_room_stupid"
        else:
            self.next_page = "briefing_room_stupid"
    
    def host_game(self):
        print "You're going to need to come up with a name for this battle. Make"
        print "it quick, son. Charlie waits for no man. The longer you take, the"
        print "more of our boys die out there. So what's it going to be?"
        game_name = raw_input(": ")
        
        if not game_name:
            self.next_page = "host_game"
            return
        
        self.game.config.game_name = str(game_name)
        
        print "Ok. Now you have to pick a port to serve this little massacre from."
        print "Just try to use your head and pick something bigger than 1024!\n"
        port = raw_input("port: ")
        if not port:
            print "Ok. You screwed it up. Now we have to start the whole thing over again!"
            self.next_page = "host_game"
            return
        
        port = int(port)
        if not port > 1024:
            print "Are you trying to get everybody killed?! I said BIGGER than 1024."
            print "Now we gotta go throught the whole thing again"
            self.next_page = "host_game"
            return
        
        print "Now you just have to tell us when to stop shooting. Set the maximum"
        print "number of kills, and when somebody gets it, we'll pack up and go home"
        print "Lets just make sure it ain't Charlie that gets it!"
        
        num_kills = raw_input(": ")
        num_kills = int(num_kills)
        self.game.config.max_kills = num_kills
        
        self.game.config.game_port = port
        self.game.config.host = True
        self.next_page = "host_lobby"
        self.game.add_local_player()
    
    def join_game(self):
        numbers = "0123456789"
        print "Here's a list of the current battles you can join up with. Choose"
        print "carfully, though. Pick the wrong one and Charlie will make a hero"
        print "out of you\n"
        
        print "[key]\tname\tip\t\tport\tplayers\topen spots"
        
        game_list = self.get_games()
        for i in range(len(game_list)):
            game = game_list[i]
            print "[%i]\t%s\t%s:\t%i\t%i\t%i" % (i+1, game['name'], game['ip'], int(game['port']), int(game['players']), int(game['open_spots']))
        
        print "\n[r] Reload Options"
        print "[b] Previous Screen"
        print "[x] Try to run home. You won't make it, but you can try."
        
        while True:
            choice = raw_input("\n: ")
            
            if choice:
                if numbers.find(choice) > -1:
                    game_num = int(choice) -1
                    if game_num >= 0:
                        if not game_num < len(game_list):
                            continue
                        if(self.do_join_game(game_list[game_num])):
                            print "Good Luck, Soldier! You're gonna need it! HAHAHA!"
                            self.next_page = "deployment"
                            break
                        else:
                            print "Sorry, Hotshot. The boy's over at '%s' don't want you. Better pick another" % game['name']
                            print "battle"
                            continue
                if choice == "r":
                    self.next_page = "join_game"
                    break
                elif choice == "b":
                    self.next_page = "briefing_room"
                    break
                elif choice == "x":
                    print "You make it out of the base alive and Charlie will still be waiting for ya!"
                    self.next_page = "exit"
                    break
                else:
                    self.next_page = "join_game"
                    break
            else:
                self.next_page = "join_game"
                break
    
    def host_lobby(self):
        self.game.config.host = True
        if not self.game.info_server_running:
            self.game.start_info_server()
            
        print "Here's where we sit and wait for anybody stupid enough to join our"
        print "company. When you say the word, we roll out! Hoo Rah!\n"
        
        for i in range(0,4):
            if(i < len(self.game.players)):
                player = self.game.players[i]
                print "(%i) %s : %s" % (i+1, player.callsign, player.addr[0])
            else:
                print "(%i) -Empty-" % (i+1)
        
        print "\n[s] ROLL OUT!!"
        print "[r] refresh list of recruits"
        print "[b] previous screen"
        print "[x] Desert. Go ahead, I know you want to. Freedom is just pass the mess hall"
        
        choice = raw_input("\n: ")
        
        if choice:
            if choice == "s":
                print "Lets MOVE OUT!!!!"
                self.next_page = "start_game"
                self.game.stop_info_server()
            elif choice == "r":
                self.next_page = "host_lobby"
            elif choice == "b":
                self.next_page = "briefing_room"
                self.game.stop_info_server()
            elif choice == "x":
                print "You make it out of the base alive and Charlie will still be waiting for ya!"
                self.next_page = "exit"
                self.game.stop_info_server()
            else:
                self.next_page = "host_lobby"
        else:
            self.next_page = "host_lobby"
    
    def deployment(self):
        print "I hope you took the time to write your parents one last time. Heh heh heh"
        print "Its too late to turn back now"
        
        if self.await_game_launch():
            print "\nOK! We Got our orders. Let HEAD OUT!!"
            self.next_page = "start_game"
                """

    def get_games(self):
        req_xml = "<tank_game_info_request></tank_game_info_request>";
        infoHandler = game_info_handler_client()
        game_list = []
        
        sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind(("", 1976))
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.settimeout(1)
        sent = sock.sendto(req_xml, ('255.255.255.255', 1976))
        for i in range(5):
            try:
                infoHandler = game_info_handler_client()
                (data, addr) = sock.recvfrom(4000)
                xml.sax.parseString(data, infoHandler)
                if infoHandler.request_type == "game_info":
                    newGame = infoHandler.game
                    newGame['ip'] = addr[0]
                    game_list.append(newGame)
            except:
                pass
        sock.close()
        return game_list
    
    def do_join_game(self):
        idx = list(self.join_games_sb.values)
        idx = int(idx[0])
        game = self.available_games[idx]
        xml_req = "<tank_game_join_request "
        xml_req+= "callsign=\"%s\" " % self.game.config.callsign
        xml_req+= "/>"
        handler = game_info_handler_client()
        
        sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("", 1976))
        sock.settimeout(5)
        sent = sock.sendto(xml_req, (game['ip'], 1976))
        accepted = False
        try:
            (data, addr) = sock.recvfrom(4000)
            if addr[0] == game['ip']:
                xml.sax.parseString(data, handler)
                if handler.request_type == "tank_game_join_response":
                    if handler.answer == "yes":
                        self.game.config.game_port = handler.game_port
                        self.game.config.game_host = (addr[0], int(handler.game_port))
                        sock.close()
                        accepted = True
                    else:
                        sock.close()
                        accepted = False
                else:
                    sock.close()
                    accepted = False
            else:
                sock.close()
                accepted = False
        except:
            sock.close()
            accepted = False
        sock.close()
        if accepted:
            self.activate_menu(self.join_lobby)
            self.game_waiter = game_launch_waiter(self.game)
            self.game_waiter.start()
    
    def set_ready(self):
        details = {}
        details['type'] = "player_ready"
        details['id'] = self.game.config.local_player.player_id
        
        if self.game.config.host:
            pygame.event.post(pygame.event.Event(pygame.USEREVENT, {'details':details}))
        else:
            sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(("", 1976))
            sock.settimeout(5)
            message = cPickle.dumps(details)
            mLen = len(message)
            resend = True
            while resend:
                sent = sock.sendto(message, (self.game.config.game_host[0], 1976))
                if not sent < mLen:
                    resend = False
            self.launch_waiter = game_launch_waiter(self.game)
            self.launch_waiter.start()
    """
    def await_game_launch(self):
        sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("", 1976))
        sock.settimeout(5)
        
        handler = game_setup_handler_client()
        for i in range(5):
            try:
                (data, addr) = sock.recvfrom(4000)
                xml.sax.parseString(data, handler)
                if handler.request_type == "tank_game_start":
                    for p in handler.players:
                        if not p['callsign'] == self.game.config.callsign:
                            newPlayer = player(p['callsign'], "peer")
                            newPlayer.start_info['start_position'] = p['start_pos']
                        else:
                            newPlayer = player(p['callsign'], "local")
                            newPlayer.start_info['start_position'] = p['start_pos']
                            newPlayer.player_id = p['player_id']
                            self.game.config.local_player = newPlayer
                        newPlayer.player_id = p['player_id']
                        self.game.players[p['player_id']] = newPlayer
                    
                    return True
                    break
            except:
                print "Error in try catch block starting at line 296 in game_menu.py"
        return False
        sock.close()
    
    def post_game(self):
        print "Stats:\nPlayer\tKills\tAssists\tDeaths\n"
        for p in self.game.players:
            play = self.game.players[p]
            if len(play.callsign) < 8:
                tabs = "\t\t"
            else:
                tabs = "\t"
            print "%s%s%i\t%i\t%i" % (play.callsign, tabs, play.kills, play.assists, play.deaths)
        
        print "\nSo What now? You up for more?"
        print "[r] Replay"
        print "[x] Go back to your home on coward island"
        
        choice = raw_input(": ")
        if choice == "x":
            self.next_page = "exit"
            print "I am literally going to shoot you myself for deserting"
        elif choice == "r":
            for p in self.game.players:
                play = self.game.players[p]
                play.kills = 0
                play.assists = 0
                play.deaths = 0
            
            if self.game.config.host:
                self.next_page = "start_game"
            else:
                self.next_page = "deployment"
                """
